<template>
  <div class="orderConfirm">
    <PageTitle title="确认订单"></PageTitle>
    <div class="skeleton" v-if="!orderInfo">
      <van-skeleton title :row="3" />
      <van-skeleton title :row="6" />
    </div>
    <div class="address" v-if="orderInfo">
      <div class="title">收货地址</div>
      <van-cell
        class="address_hint"
        title="设置收货地址"
        is-link
        @click="clickAddress"
        v-if="!curAddress"
      />
      <div class="address_info" @click="clickAddress" v-if="curAddress">
        <div class="info_t">
          <span class="name">收货人：{{ curAddress.name }}</span>
          <span class="phone">{{ curAddress.tel }}</span>
        </div>
        <div class="info_b">
          <span class="defaultIcon" v-show="curAddress.isDefault">默认</span
          >{{ curAddress.address }}
        </div>
      </div>
    </div>
    <div class="cart" v-if="orderInfo">
      <div class="title">共{{ orderInfo.cartInfo.length }}件商品</div>
      <div class="cartList">
        <div
          class="card"
          v-for="item in orderInfo.cartInfo"
          :key="item.id"
          @click="$router.push('/detail/' + item.productInfo.id)"
        >
          <van-card
            :num="item.cart_num"
            :price="item.truePrice"
            :desc="item.productInfo.attrInfo.suk"
            :title="item.productInfo.store_name"
            :thumb="item.productInfo.image"
          />
        </div>
      </div>
    </div>
    <div class="info" v-if="orderInfo">
      <van-cell
        title="优惠券"
        :value="'暂无可用优惠券'"
        is-link
        @click="couponShow = true"
      />
      <van-cell
        title="积分抵扣"
        class="integral"
        @click="integralChecked = !integralChecked"
        clickable
      >
        <template #right-icon>
          <div class="integral_r">
            当前积分<span>{{ orderInfo.userInfo.integral }}</span
            ><van-icon
              :name="integralChecked ? 'checked' : 'circle'"
              :color="integralChecked ? '#25c9c3' : '#c8c9cc'"
            ></van-icon>
          </div>
        </template>
      </van-cell>
      <van-cell
        title="会员优惠"
        :value="`-￥${orderInfo.priceGroup.vipPrice}`"
      />
      <van-cell
        title="快递费用"
        :value="`${
          orderInfo.priceGroup.storePostage
            ? `￥${orderInfo.priceGroup.storePostage}`
            : '免运费'
        }`"
      />
      <van-field
        v-model="explain"
        rows="2"
        autosize
        label="备注说明"
        type="textarea"
        maxlength="150"
        placeholder="填写备注信息"
        input-align="right"
        show-word-limit
      />
    </div>
    <div class="payType" v-if="orderInfo">
      <div class="title">支付方式</div>
      <div class="btnList">
        <div :class="['btn', { active: useWeixin }]" @click="useWeixin = true">
          <div class="btn_l">
            <van-icon name="wechat-pay" color="#22ac38"></van-icon>微信支付
          </div>
          <div class="btn_r"><span>微信快捷支付</span></div>
        </div>
        <div
          :class="['btn', { active: !useWeixin }]"
          @click="useWeixin = false"
        >
          <div class="btn_l">
            <van-icon name="gold-coin" color="#fe960f"></van-icon>余额支付
          </div>
          <div class="btn_r">
            <span>可用余额：{{ orderInfo.userInfo.now_money }}</span>
          </div>
        </div>
      </div>
    </div>
    <div class="total" v-if="orderComputed">
      <div class="title">合计</div>
      <div class="totalCell">
        <van-cell
          title="商品总价"
          :value="`￥${orderComputed.result.total_price}`"
        />
        <van-cell
          title="运费"
          v-if="orderComputed.result.pay_postage"
          :value="`+￥${orderComputed.result.pay_postage}`"
        />
        <van-cell
          title="积分抵扣"
          v-if="orderComputed.result.deduction_price"
          :value="`-￥${orderComputed.result.deduction_price}`"
        />
      </div>
    </div>
    <div class="bottomBar" v-if="orderComputed">
      <div class="bottom_l">
        支付金额：
        <span class="totalPrice">¥{{ orderComputed.result.pay_price }}</span>
      </div>
      <van-button round color="#25c9c3" class="btn" @click="orderConfirm"
        >立即支付</van-button
      >
    </div>
    <van-action-sheet v-model="couponShow" title="优惠券" class="coupon">
      <van-empty image="error" description="暂无优惠券可使用" />
    </van-action-sheet>
    <van-popup v-model="showAddress" position="bottom" class="addressList">
      <div class="popupTitle">
        选择地址
        <van-icon name="cross" @click="showAddress = false"></van-icon>
      </div>
      <div class="content">
        <van-loading v-if="!addressList" />
        <van-address-list
          v-if="addressList"
          v-model="addressId"
          :list="addressList"
          default-tag-text="默认"
          @select="showAddress = false"
          @add="$router.push('/address/edit')"
          @edit="
            $router.push({
              name: 'AddressEdit',
              params: {
                addressInfo: $event,
              },
            })
          "
        />
      </div>
    </van-popup>
  </div>
</template>

<script>
import PageTitle from "@/components/PageTitle";
import { mapMutations } from "vuex";
export default {
  name: "OrderConfirm",
  data() {
    return {
      orderInfo: null,
      orderComputed: null,
      couponShow: false,
      integralChecked: false,
      explain: "",
      useWeixin: false,
      showAddress: false,
      addressList: null,
      addressId: null,
    };
  },
  props: ["cartId"],
  components: {
    PageTitle,
  },
  watch: {
    cartId() {
      let newObj = {
        orderInfo: null,
        orderComputed: null,
        couponShow: false,
        integralChecked: false,
        explain: "",
        useWeixin: false,
        showAddress: false,
        addressList: null,
        addressId: null,
      };
      Object.keys(newObj).forEach((key) => {
        this[key] = newObj[newObj];
      });
      this.getOrderInfo();
    },
    integralChecked() {
      if (this.orderInfo) this.getOrderComputed();
    },
    useWeixin() {
      if (this.orderInfo) this.getOrderComputed();
    },
    addressId() {
      if (this.orderInfo) this.getOrderComputed();
    },
  },
  activated() {
    this.getOrderInfo();
    if (this.showAddress) this.getAddressList();
  },
  computed: {
    curAddress() {
      if (this.addressList) {
        return this.addressList.filter((a) => a.id == this.addressId)[0];
      } else if (this.orderInfo && this.orderInfo.addressInfo) {
        return {
          id: this.orderInfo.addressInfo.id,
          name: this.orderInfo.addressInfo.real_name,
          tel: this.orderInfo.addressInfo.phone,
          address: `${this.orderInfo.addressInfo.province} ${this.orderInfo.addressInfo.city} ${this.orderInfo.addressInfo.district} ${this.orderInfo.addressInfo.detail}`,
          isDefault: true,
        };
      } else {
        return null;
      }
    },
  },
  methods: {
    ...mapMutations(["changeLoading"]),
    getOrderInfo() {
      this.changeLoading(true);
      this.$axios
        .post("/api/order/confirm", {
          cartId: this.cartId,
        })
        .then((d) => {
          this.changeLoading(false);
          console.log("order/confirm", d.data);
          if (d.data.status == 200) {
            this.orderInfo = d.data.data;
            this.addressId = this.orderInfo.addressInfo
              ? this.orderInfo.addressInfo.id
              : null;
            this.getOrderComputed();
          } else if (d.data.status == 410000) {
            this.$toast.fail("请重新登录");
            this.$store.commit("loginOut");
            this.$router.push("/login");
          } else {
            this.$toast.fail(d.data.msg);
            this.$router.go(-1);
          }
        });
    },
    getOrderComputed() {
      this.changeLoading(true);
      this.$axios
        .post(`/api/order/computed/${this.orderInfo.orderKey}`, {
          addressId: this.addressId,
          couponId: 0,
          payType: this.useWeixin ? "weixin" : "yue",
          useIntegral: Number(this.integralChecked),
        })
        .then((d) => {
          this.changeLoading(false);
          console.log("order/computed", d.data);
          if (d.data.status == 200) {
            this.orderComputed = d.data.data;
          } else if (d.data.status == 410000) {
            this.$toast.fail("请重新登录");
            this.$store.commit("loginOut");
            this.$router.push("/login");
          } else {
            this.$toast.fail(d.data.msg);
            this.$router.go(-1);
          }
        });
    },
    orderConfirm() {
      if (!this.addressId) {
        this.$toast("请选择收货地址");
        return;
      }
      this.changeLoading(true);
      this.$axios
        .post(`/api/order/create/${this.orderInfo.orderKey}`, {
          addressId: this.addressId,
          couponId: 0,
          payType: this.useWeixin ? "weixin" : "yue",
          useIntegral: Number(this.integralChecked),
          mark: this.explain,
        })
        .then((d) => {
          this.changeLoading(false);
          console.log("order/create", d.data);
          if (d.data.status == 200) {
            this.$router.replace(`/order/status/${d.data.data.result.orderId}`);
          } else if (d.data.status == 410000) {
            this.$toast.fail("请重新登录");
            this.$store.commit("loginOut");
            this.$router.push("/login");
          } else {
            this.$toast.fail(d.data.msg);
            this.$router.go(-1);
          }
        });
    },
    getAddressList() {
      this.addressList = null;
      this.$axios.get("/api/address/list").then((d) => {
        console.log("address/list", d.data);
        if (d.data.status == 200) {
          let list = [];
          d.data.data.map((item) => {
            let obj = {
              id: item.id,
              name: item.real_name,
              tel: item.phone,
              address: `${item.province} ${item.city} ${item.district} ${item.detail}`,
              isDefault: item.is_default,
            };
            list.push(obj);
          });
          this.addressList = list;
        } else if (d.data.status == 410000) {
          this.$toast.fail("请重新登录");
          this.$store.commit("loginOut");
          this.$router.push("/login");
        }
      });
    },
    clickAddress() {
      this.showAddress = true;
      if (!this.addressList) this.getAddressList();
    },
    addAddress(e) {
      console.log("addAddress", e);
    },
    editAddress(e) {
      console.log("editAddress", e);
    },
  },
};
</script>

<style lang="less" scoped>
.orderConfirm {
  padding-top: 56px;
  padding-bottom: 50px;
  .pageTitle {
    position: fixed;
    z-index: 999;
    left: 0;
    top: 0;
    width: 100%;
  }
  & > div .title {
    padding: 0 15px;
    height: 40px;
    line-height: 40px;
    font-size: 14px;
    background: #fff;
    border-bottom: 1px solid #f5f5f5;
  }
  .skeleton {
    padding: 0 20px;
    .van-skeleton {
      padding: 30px 0;
    }
  }
  .address {
    background: #fff;
    margin-top: 15px;
    .address_hint {
      padding: 28px 16px;
    }
    .address_info {
      padding: 15px 20px;
      font-size: 13px;
      line-height: 25px;
      position: relative;
      &:active {
        background: #f2f3f5;
      }
      .info_t {
        display: flex;
        justify-content: space-between;
      }
      .info_b {
        color: #868686;
        .defaultIcon {
          background: #25c9c3;
          border-radius: 999px;
          color: #fff;
          margin-right: 8px;
          padding: 1px 4px;
          font-size: 12px;
        }
      }
    }
    .address_hint::before,
    .address_info::before {
      content: "";
      display: block;
      position: absolute;
      right: 0;
      bottom: 0;
      left: 0;
      height: 2px;
      background: repeating-linear-gradient(
        -45deg,
        #ff6c6c 0,
        #ff6c6c 20%,
        rgba(0, 0, 0, 0) 0,
        rgba(0, 0, 0, 0) 25%,
        #1989fa 0,
        #1989fa 45%,
        rgba(0, 0, 0, 0) 0,
        rgba(0, 0, 0, 0) 50%
      );
      background-size: 80px;
    }
  }
  .cart {
    margin-top: 15px;
    .cartList {
      .card {
        padding: 0 20px;
        background: #fff;
        &:active {
          background: #f2f3f5;
        }
        &:not(:first-child) .van-card {
          border-top: 1px solid #f5f5f5;
        }
        .van-card {
          padding: 15px 0;
          background: inherit;
          .van-card__thumb {
            height: 75px;
            width: 75px;
          }
          .van-card__content {
            min-height: 75px;
          }
        }
      }
    }
  }
  .info {
    margin-top: 15px;
    .integral {
      .integral_r {
        display: flex;
        align-items: center;
        span {
          color: #25c9c3;
          margin: 0 5px;
        }
        .van-icon {
          font-size: 18px;
        }
      }
    }
  }
  .payType {
    margin-top: 15px;
    .btnList {
      padding: 20px;
      font-size: 14px;
      background: #fff;
      .btn {
        height: 38px;
        border-radius: 5px;
        border: 1px solid #eee;
        display: flex;
        position: relative;

        &:not(:last-of-type) {
          margin-bottom: 10px;
        }
        &::after {
          content: "";
          display: block;
          width: 1px;
          height: 50%;
          background: #eee;
          position: absolute;
          z-index: 9;
          left: 50%;
          top: 50%;
          transform: translate(-50%, -50%);
        }
        .btn_l,
        .btn_r {
          flex: 1;
          display: flex;
          justify-content: center;
          align-items: center;
          .van-icon {
            font-size: 18px;
            margin-right: 5px;
          }
          span {
            color: #ccc;
          }
        }
        .btn_r {
          font-size: 13px;
        }
        &.active {
          color: #24c1bb;
          font-weight: normal;
          border-color: #24c1bb;
          box-shadow: 0 0 3px rgba(36, 193, 187, 0.3);
          &::after {
            background: #24c1bb;
          }
          .btn_r {
            span {
              color: #24c1bb;
            }
          }
        }
      }
    }
  }
  .total {
    margin-top: 15px;
    background: #fff;
    .totalCell {
      .van-cell {
        padding: 10px 20px;
      }
    }
  }
  .bottomBar {
    position: fixed;
    bottom: 0;
    left: 0;
    width: 100%;
    padding: 0 15px;
    box-sizing: border-box;
    height: 50px;
    background: #fff;
    display: flex;
    align-items: center;
    justify-content: space-between;
    border-top: 1px solid #f5f5f5;
    box-shadow: 0 0 1px rgba(0, 0, 0, 0.01);
    .bottom_l {
      font-size: 14px;
      display: flex;
      align-items: center;
      .totalPrice {
        font-size: 18px;
        color: #25c9c3;
      }
    }
    .van-button {
      height: 30px;
      margin-left: 15px;
    }
  }
  .addressList {
    overflow: hidden;
    border-radius: 16px 16px 0 0;
    background: #fff;
    z-index: 0;
    .popupTitle {
      font-weight: 500;
      line-height: 48px;
      font-size: 16px;
      text-align: center;
      position: absolute;
      z-index: 99;
      left: 0;
      top: 0;
      width: 100%;
      box-sizing: border-box;
      background: #fff;
      .van-icon {
        position: absolute;
        right: 0;
        top: 0;
        color: #c8c9cc;
        line-height: inherit;
        font-size: 22px;
        padding: 0 16px;
      }
    }
    .content {
      padding-top: 48px;
      max-height: calc(80vh - 48px);
      overflow-y: auto;
      .van-loading {
        color: #25c9c3;
        text-align: center;
        padding: 100px 0;
        .van-loading__spinner {
          width: 40px;
          height: 40px;
        }
      }
      .van-address-list {
        .van-address-item {
          ::v-deep.van-radio__icon--checked .van-icon {
            background-color: #25c9c3;
            border-color: #25c9c3;
          }
          .van-address-item__tag.van-tag--danger {
            background-color: #25c9c3;
          }
        }
        .van-address-list__bottom {
          .van-address-list__add.van-button--danger {
            background-color: #25c9c3;
            border-color: #25c9c3;
          }
        }
      }
    }
  }
}
</style>